package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrdersService ordersService;


    @Override
    @Transactional
    public void submit(Orders orders) {
        long ordersId = IdWorker.getId();//生成订单号
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);//查询用户数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());//查询地址数据
        BigDecimal amount = new BigDecimal(0);//总金额


        //查询当前用户的购物车数据
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomerException("购物车为空，不能下单");
        }

        //添加订单详情表的数据 多条
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(ordersId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());//小计
            orderDetail.setImage(cart.getImage());
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
            orderDetailList.add(orderDetail);
        }

        //订单 1个订单
        //组装订单数据
        orders.setId(ordersId);
        orders.setNumber(System.currentTimeMillis()+"");
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(amount);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //向订单表插入数据，一条数据
        this.save(orders);
        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车数据
        shoppingCartService.remove(queryWrapper);

    }

    @Override
    public R<Page<Orders>> pageWithDish(Integer page, Integer pageSize, String number) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //设置条件构造器
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(number!=null,"number",number);
        queryWrapper.orderByDesc("checkout_time");
        ordersService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }
}
